<template>
    <div style="display: flex;">
        <div class="left" style="width: 300px;background: #F0F3F5">
            <a-spin :spinning="loading">
                <a-directory-tree :tree-data="treeData" @select="onSelect" @expand="onExpand" :defaultExpandAll="true" @update:expandedRowKeys="handle"
                    :replace-fields="{ children: 'children', key: 'id', value: 'name', title: 'name' }" />
            </a-spin>
        </div>
        <div class="right" style="flex:1">
            <div style="height:32px;line-height: 32px;border-bottom: 1px solid #D8D8D8;border-top: 1px solid #D8D8D8;">
                <div style="margin-left: 8px;">{{ currentDirectory }}</div>
            </div>
            <div style="margin-top: 12px;margin-left: 16px;">
                <div style="display: flex;justify-content: space-between;">
                    <a-button type='primary' @click="handleCreate">
                        <Iconfont class="icon button-icon-style" type="icon-new16f"></Iconfont>
                        {{ $t('Create') }}
                    </a-button>
                    <div style="display: flex;">
                        <div style="display: flex;">
                            <div style="width: 100px;margin-top: 4px;">{{ $t('文件名称') }}：</div>
                            <a-input v-model="input" :placeholder="$t('Enter') + $t('文件名称')" />
                        </div>
                        <a-button type='primary' style="margin-left: 8px;" @click="handleSearch">
                            <Iconfont class="icon button-icon-style" type="icon-search16f"></Iconfont>
                            {{ $t('Search') }}
                        </a-button>
                    </div>
                </div>
                <a-table style="margin-top:16px" class="bigstyle" rowKey="id" :columns='columns' :loading="loading"
                    :dataSource='currentChildren' :locale="defaultSetting" :pagination='pagination' size='small'
                    >
                    <template slot="name" slot-scope="name">
                        <span style="color: #006DB8;cursor: pointer" @click="handleDetail(name)">{{ name }}</span>
                    </template>
                    <template slot="operate" slot-scope='text, record'>
                        <div style="display: flex;justify-content: space-between;">
                            <a-tooltip placement='top'>
                                <template slot='title'>
                                    <span>{{ $t('创建共享') }}</span>
                                </template>
                                <Iconfont class="icon table-operation-icon" type="icon-share16f" @click="handleShare">
                                </Iconfont>
                                <!-- <span style="color: #006DB8;cursor: pointer" @click="handleCheck(record)">{{ $t('创建共享')
                                }}</span> -->
                            </a-tooltip>
                            <a-tooltip placement='top'>
                                <template slot='title'>
                                    <span>{{ $t('创建配额') }}</span>
                                </template>
                                <Iconfont class="icon table-operation-icon" type="icon-quota16f1"
                                    @click="handleQuota(record)"></Iconfont>
                                <!-- <span style="color: #006DB8;cursor: pointer" @click="handleSynchronize(record)">{{
                                    $t('创建配额')
                                }}</span> -->
                            </a-tooltip>
                            <a-tooltip placement='top'>
                                <template slot='title'>
                                    <span>{{ $t('Set-pool') }}</span>
                                </template>
                                <Iconfont class="icon table-operation-icon" type="icon-pool16l" @click="handlePool(record)">
                                </Iconfont>
                                <!-- <span style="color: #006DB8;cursor: pointer" @click="handleSynchronize(record)">{{
                                    $t('创建配额')
                                }}</span> -->
                            </a-tooltip>
                            <a-tooltip placement='top'>
                                <template slot='title'>
                                    <span>{{ $t('快照配置') }}</span>
                                </template>
                                <Iconfont class="icon table-operation-icon" type="icon-photo16f" @click="handleSnapshot">
                                </Iconfont>
                                <!-- <span style="color: #006DB8;cursor: pointer" @click="handleSnapshot(record)">{{ $t('快照配置')
                                }}</span> -->
                                <!-- <Iconfont class="icon table-operation-icon" type="icon-edit16f" @click="handleEdit(record)"></Iconfont> -->
                            </a-tooltip>
                            <a-tooltip placement='top'>
                                <template slot='title'>
                                    <span>{{ $t('Delete') }}</span>
                                </template>
                                <Iconfont class="icon table-operation-icon" type="icon-delete16f"
                                    @click="handleDelete(record.name)"></Iconfont>
                                <!-- <span style="color: #E01628;cursor: pointer" @click="handleDelete(record)">{{ $t('Delete')
                                }}</span> -->
                            </a-tooltip>
                        </div>
                    </template>
                </a-table>
            </div>
        </div>

        <createDirectory ref="createRef" />
        <PoolDialog ref="poolRef" @get-list="getList" />
        <ShareDialog ref="shareRef" @change-tab="handleTab" />

    </div>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
import createDirectory from './createDirectory.vue'
import PoolDialog from './poolDialog'
import ShareDialog from './shareDialog.vue'

export default {
    components: { createDirectory, EmptyData, PoolDialog, ShareDialog },
    data() {
        return {
            treeData: [],
            expandedKeys: [],
            path: '',
            currentDirectory: '',
            currentChildren: [],
            input: '',
            loading: false,
            defaultSetting: { emptyText: <EmptyData /> },
            pagination: {
                defaultPageSize: 10,
                showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
                showSizeChanger: true,
                pageSizeOptions: ['5', '15', '20', '25'],
                onShowSizeChange: (current, pageSize) => this.pageSize = pageSize,
                buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
            },
            columns: [
                { title: this.$t('接入名称'), dataIndex: 'name', key: 'name', scopedSlots: { customRender: 'name' } },
                { title: this.$t('Operate'), key: "operate", scopedSlots: { customRender: 'operate' }, width: 200 }
            ],
            header: '',
            expandedRowKeys: [],
        }
    },
    mounted() {
        this.getList()
    },
    methods: {
        async getList(file_path = '') {
            this.loading = true
            const { data } = await this.$api.directory.getDirectoryListApi({ file_path })
            if (file_path === '') {
                this.header = data[0].name
            }
            const itemList = data.map(item => {
                // item.id = 0
                // this.expandedKeys.push(0)
                if (item.children) {
                    item.children.map(async (subItem, index) => {
                        // if (subItem.id && this.expandedKeys.indexOf(subItem.id) !== '-1') this.expandedKeys.push(subItem.id)
                        if (subItem.child) {
                            subItem.children = [{ name: '-' }]
                        }
                    })
                }
                return item
            })
            this.treeData = itemList
            this.loading = false
        },
        async onSelect(keys, event) {
            this.loading = true
            const dom = event.selectedNodes[0].dataRef
            const children = dom.children
            let id = dom.id
            let value = dom.name
            let level = dom.lv
            let parent = dom.pre_dir
            let file_path = ''
            if (level == '1') file_path = value
            if (Number(level) > 1) file_path = parent + '/' + value
            if (children && value !== this.header) {
                const { data } = await this.$api.directory.getDirectoryListApi({ file_path })
                const list = data[0].children.map((item, index) => {
                    // if (item.id && this.expandedKeys.indexOf(item.id) !== '-1') this.expandedKeys.push(item.id)
                    if (item.child) {
                        item.children = [{ name: '-' }]
                    }
                    return item
                })
                this.deepQuery(this.treeData, id, list)
                this.currentChildren = dom.children
            }
            this.loading = false
        },
        async onExpand(list, event) {
            this.loading = true
            const dom = event.node.dataRef
            const children = dom.children
            let id = dom.id
            let value = dom.name
            let level = dom.lv
            let parent = dom.pre_dir
            let file_path = ''
            const path = this.getPathByKey(id, this.treeData)
            if (level == '1') file_path = value
            if (Number(level) > 1) file_path = parent + '/' + value
            if (children && value !== this.header) {
                const { data } = await this.$api.directory.getDirectoryListApi({ file_path })
                const list = data[0].children.map((item, index) => {
                    if (item.child) {
                        item.children = [{ name: '-' }]
                    }
                    return item
                })
                this.deepQuery(this.treeData, id, list)
                this.currentChildren = dom.children
            }
            this.currentDirectory = path
            this.loading = false
        },
        deepQuery(tree, id, children) {
            const list = []
            function deepSearch(tree, id) {
                for (const item of tree) {
                    if (item.children && item.children.length > 0) {
                        deepSearch(item.children, id);
                    }
                    if (id === item.id) {
                        item.children = children
                        break;
                    }
                }
            }
            deepSearch(tree, id);
        },
        getPathByKey(curKey, data) {
            let result = []; // 记录路径结果
            let traverse = (curKey, path, data) => {
                if (data.length === 0) {
                    return;
                }
                for (let item of data) {
                    path.push(item.name);
                    if (item.id === curKey) {
                        result = JSON.parse(JSON.stringify(path));
                        return;
                    }
                    const children = Array.isArray(item.children) ? item.children : [];
                    traverse(curKey, path, children); // 遍历
                    path.pop(); // 回溯
                }
            }
            traverse(curKey, [], data);
            const current = result.join('/')
            this.path = '/' + result.splice(1).join('/')
            return current
        },
        handleCreate() {
            this.$refs.createRef.isShow = true
        },
        handleShare() {
            this.$refs.shareRef.isShow = true
            this.$refs.shareRef.form.dir_name = this.path
        },
        handleSnapshot() {
            this.$router.push({ path: '/snapshotConfig', query: { name: this.currentDirectory } })
        },
        handleQuota() {
            this.$router.push({ path: '/createQuota', query: { name: this.currentDirectory } })
        },
        handleTab(item) {
            this.$emit('to-share', item)
        },
        async handlePool(item) {
            this.$refs.poolRef.isShow = true
            this.$refs.poolRef.getList()
            this.$refs.poolRef.form.fs_name = item.fs_name
            this.$refs.poolRef.form.dir_name = this.path
        },
        async handleSearch() {
            // const { data: { params } } = await this.$api.directory.searchDirectoryListApi({ dir_name: this.input })
            // this.expandedKeys = params.map(item => item.id)
            // console.log(this.expandedKeys)
            // this.expandedKeys.push(0)
        },
        async handleDelete(dir_name) {
            this.loading = true
            let _this = this
            this.$confirm({
                title: this.$t('删除文件'),
                content: this.$t('删除文件名为') + `${dir_name}` + this.$t('后，将无法恢复！您确定要删除吗？'),
                cancelText: this.$t('Cancel'),
                okText: this.$t('Sure'),
                okType: 'danger',
                icon: 'close-circle',
                async onOk() {
                    const { data } = await _this.$api.directory.deleteDirectoryApi({ dir_name })
                    _this.model(data.id) //返回模板
                    _this.notice(data.id, data.params, data.flag) //通知列表显示
                    if (data.flag == '0') _this.getList()
                },
                onCancel() {
                }
            })
            this.loading = false
        },
    },
    handle() {
        console.log(111)
    }
}
</script>